<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入活动名称" />
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="活动时间" prop="time">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-date-picker
              v-model="formData.startTime"
              type="date"
              value-format="x"
              placeholder="选择活动开始时间"
              class="w-100%"
            />
          </el-col>
          <el-col :span="12">
            <el-date-picker
              v-model="formData.endTime"
              type="date"
              value-format="x"
              placeholder="选择活动结束时间"
              class="w-100%"
            />
          </el-col>
        </el-row>
      </el-form-item>
    <el-form-item> 
      <el-button @click="spuSelectRef.open()">选择商品</el-button>
    </el-form-item>
      <el-form-item label="关联商品" prop="spuIds">
        <div class="mt-2 border rounded p-2">
          <div v-if="spuList.length === 0" class="text-gray-400 text-center py-4">
            暂无选择商品
          </div>
          <el-table v-else :data="spuList" :stripe="true" class="mb-4">
            <el-table-column label="商品图片" align="center" width="100">
              <template #default="{ row }">
                <el-image
                  :src="row.picUrl"
                  class="h-40px w-40px rounded"
                  :preview-src-list="[row.picUrl]"
                  preview-teleported
                >
                  <template #error>
                    <div class="h-40px w-40px flex items-center justify-center bg-gray-100 rounded">
                      <Icon icon="ep:picture" class="text-xl text-gray-400" />
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="name" min-width="350" show-overflow-tooltip />
            <el-table-column label="商品价格" prop="price" min-width="100">
              <template #default="{ row }"> 
                ￥{{ fenToYuan(row.price) }}
              </template>
            </el-table-column>
            <el-table-column label="商品库存" prop="stock" min-width="100" />
            <el-table-column label="商品状态" prop="status" min-width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '上架' : '下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="{ $index }">
                <el-button
                  type="primary"
                  circle
                  size="small"
                  @click="removeSpu($index)"
                >
                  <Icon icon="ep:delete" />
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item label="活动备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入活动备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <SpuSelectDialog ref="spuSelectRef" :isSelectSku="false" @confirm="selectSpu" />
</template>
<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { ActivityTopicApi, ActivityTopicVO } from '@/api/mall/promotion/activityTopic'
import SpuSelectDialog from '@/views/mall/product/spu/components/SpuSelectDialog.vue'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { fenToYuan } from '@/utils'
/** 活动主题 表单 */
defineOptions({ name: 'ActivityTopicForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  status: undefined,
  remark: undefined,
  startTime: undefined,
  endTime: undefined,
  sort: undefined,
  spuIds: [] as number[]
})
const formRules = reactive({
  name: [{ required: true, message: '活动名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '活动状态不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '活动开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '活动结束时间不能为空', trigger: 'blur' }],
  spuIds: [{ required: true, message: '请选择关联商品', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

// ================= 商品选择相关 =================
const spuSelectRef = ref() // 商品选择 Ref
const spuList = ref<any[]>([]) // 选择的 spu

const removeSpu = (index: number) => {
  spuList.value.splice(index, 1)
  formData.value.spuIds.splice(index, 1)
}

const selectSpu = async (spuIds: number[]) => {
  debugger
  const res = await ProductSpuApi.getSpuDetailList(spuIds)
  spuList.value = res
  formData.value.spuIds = spuIds
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await ActivityTopicApi.getActivityTopicById(id)
      formData.value = data
      // 加载已关联的SPU详情
      if (data.spuIds?.length) {
        await selectSpu(data.spuIds)
      }
    } finally {
      formLoading.value = false
    }
  }else{
    spuList.value = []
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ActivityTopicVO
    if (formType.value === 'create') {
      await ActivityTopicApi.createActivityTopic(data)
      message.success(t('common.createSuccess'))
    } else {
      await ActivityTopicApi.updateActivityTopic(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    status: undefined,
    remark: undefined,
    startTime: undefined,
    endTime: undefined,
    sort: undefined,
    spuIds: []
  }
  formRef.value?.resetFields()
}
</script>
